package com.corn.security;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/11/25 17:55
 */

public class RSATest {

    public static void main(String[] args) {
        try {

            KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();

            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
            // 使用KeyFactory生成秘钥对方法
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            // 生成私钥
            KeySpec keySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
            PublicKey pk = keyFactory.generatePublic(keySpec);
            cipher.init(Cipher.ENCRYPT_MODE, pk);
            byte[] en = cipher.doFinal("test666".getBytes());
            String base64 = Base64.getEncoder().encodeToString(en);
            System.out.println(base64);

            Cipher cipher1 = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
            Key pri = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded()));
            cipher1.init(Cipher.DECRYPT_MODE, pri);
            byte[] result = cipher1.doFinal(Base64.getDecoder().decode(base64));
            System.out.println(new String(result));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
